﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Co9320.NamaAlert.Model;
using System.Linq;

namespace Co9320.NamaAlert.Engine.Lists
{

	internal interface IInspectionList:IEnumerable<LiveProgram>
	{
		InspectionResult Inspect(LiveProgram InspectionTarget);

		DateTime CommunityLatestPubTime
		{
			get;
		}
	}

	internal class InspectionList:IInspectionList
	{
		Dictionary<int,LiveProgram> ExistsDict_;

		public InspectionList()
		{
			ExistsDict_ = new Dictionary<int, LiveProgram>();
			CommunityLatestPubTime = DateTime.MinValue;
		}

		public DateTime CommunityLatestPubTime
		{
			get;
			private set;
		}

		public InspectionResult Inspect(LiveProgram InspectionTarget)
		{
			if (InspectionTarget.StartDateTime >= CommunityLatestPubTime)
			{
				return InspectionResult.InspectionOutOfRange;
			}
			else if (ExistsDict_.ContainsKey(InspectionTarget.Id))
			{
				return InspectionResult.Exists;
			}
			else
			{
				return InspectionResult.DetectOffAir;
			}
		}

		public void Add(LiveProgram item)
		{
			Debug.Assert(item!=null);

			if (item.Station.Kind == StationKind.Community &&
				item.StartDateTime>CommunityLatestPubTime)
			{
				CommunityLatestPubTime = item.StartDateTime;
			}

			if (!ExistsDict_.ContainsKey(item.Id))
			{
				ExistsDict_.Add(item.Id,item);
			}
		}

		public void Add(FeedingLivePrograms List)
		{
			Debug.Assert(List != null);

			for (int i = 0; i < List.Count; i++)
			{
				Add(List[i]);
			}
		}

		#region IEnumerable<LiveProgram> メンバ

		public IEnumerator<LiveProgram> GetEnumerator()
		{
			return ExistsDict_.Select(tmp => tmp.Value).GetEnumerator();
		}

		#endregion

		#region IEnumerable メンバ

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			return this.GetEnumerator();
		}

		#endregion
	}
}
